package yuan.datastructure.list;

public class ArrayList implements List{
	private static final int INITIALIZED_DATA_SIZE	=	10;
	
	private Object[] data;
	private int currentIndex = 0;
	private int size = 0;
	
	public ArrayList(){
		data = new Object[INITIALIZED_DATA_SIZE];
	}
	
	@Override
	public void clear() {
		while(size>0)
			delete(size-1);
	}

	@Override
	public boolean isEmpty() {
		return size==0;
	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public Object getElementAt(int i) {
		if (i<0 || i>(size-1))
			return null;
		return data[i];
	}

	@Override
	public int locateElement(Object e) {
		for (int i=0; i<size;i++){
			if (e.equals(data[i]))
				return i;
		}
		return -1;
	}

	@Override
	public Object first() {
		if (size == 0)
			return null;
			
		currentIndex = 0;
		return data[currentIndex];
	}

	@Override
	public Object prior() {
		if (currentIndex==0)
			return null;//throw new IllegalArgumentException("can't get prior since it's first element");
		currentIndex--;
		return data[currentIndex];
	}

	@Override
	public Object next() {
		if (currentIndex==size-1)
			return null;//throw new IllegalArgumentException("can't get prior since it's last element");
		currentIndex++;
		return data[currentIndex];
	}

	@Override
	public Object last() {
		if (size == 0)
			return null;
		
		currentIndex = size-1;
		return data[currentIndex];
	}

	@Override
	public void insert(Object e) {
		insert(e, size);
	}

	@Override
	public void insert(Object e, int i) {
		if (size == data.length){
			Object[] newData = new Object[data.length+INITIALIZED_DATA_SIZE];
			for (int l=0;l<size;l++)
				newData[l] = data[l];
			
			data = newData;
		}
		
		if (size == i)
			data[i] = e;
		else{
			for (int l=size;l>i;l--){
				data[l] = data[l-1];
			}
			
			data[i] = e;
		}
		
		size++;
	}

	@Override
	public void delete(Object e) {
		int index = locateElement(e);
		if (index == -1)
			throw new IllegalArgumentException("can't find object in list:"+e);
		
		delete(index);
	}

	@Override
	public void delete(int i) {
		if (i<0 || i>(size-1))
			throw new IllegalArgumentException("input index is not valid i:"+i+" size:"+size);
		
		for (int l=i;l<size-1;l++)
			data[l] = data[l+1];
		size--;
	}

}
